package com.ntt.benew.dictionary.adapter

import android.animation.AnimatorInflater
import android.animation.StateListAnimator
import android.content.Context
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.gson.internal.LinkedTreeMap
import com.google.gson.reflect.TypeToken
import com.ntt.benew.dictionary.R
import com.ntt.benew.dictionary.constants.Constants
import com.ntt.benew.dictionary.entity.DictWordEntity
import com.ntt.benew.dictionary.entity.YDDerivatives
import com.ntt.benew.dictionary.entity.YDPhrasesEntity
import com.ntt.benew.dictionary.entity.YDRelatedWords
import com.ntt.benew.dictionary.listener.IChildClickListener
import com.ntt.benew.dictionary.utils.setDrawableBackground
import com.ntt.benew.dictionary.view.BorderedTextView
import com.ntt.benew.dictionary.view.WordDetailTitleView
import com.ntt.core.nlogger.NLogger

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/11/3
 * Time: 15:13
 */
class DictWordAdapter(context: Context, data: List<DictWordEntity>? = null) :
    RecyclerView.Adapter<DictWordAdapter.ViewHolder>() {


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {}

    val mContext: Context

    private var mData: List<DictWordEntity>? = null
        get() {
            if (field == null) {
                return arrayListOf()
            }
            return field
        }

    init {
        mContext = context
        mData = data
    }

    /**
     * 子view点击监听
     */
    var mOnChildClickListener: IChildClickListener? = null
        set(value){
            NLogger.d("DictWordAdapter 修改了监听 $value")
            field = value
        }



    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = when (viewType) {
//            TYPE_EXPLAIN_ITEM ->
            Constants.TYPE_PHRASE_ITEM,
            Constants.TYPE_EXPAND_ITEM,
            Constants.TYPE_RELATED_ITEM -> LayoutInflater.from(mContext)
                .inflate(R.layout.item_recycler_view, parent, false)
//            TYPE_EMPTY ->
            else -> LayoutInflater.from(mContext)
                .inflate(R.layout.item_explain_layout, parent, false)
        }
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return mData!!.size
    }

    override fun getItemViewType(position: Int): Int {
        if (mData.isNullOrEmpty()) {
            return Constants.TYPE_EMPTY
        }
        return mData!![position].type
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        mData?.get(position)?.let {
            holder.itemView.findViewById<WordDetailTitleView>(R.id.title).setText(it.titleTxt)
            when (it.type) {
                Constants.TYPE_EXPLAIN_ITEM -> {
                    holder.itemView.findViewById<LinearLayout>(R.id.ll_content).apply {
                        removeAllViews()
                        addView(
                            renderExplain(it.values)
                        )
                    }
                }

                Constants.TYPE_PHRASE_ITEM -> {
                    val recyclerView = holder.itemView.findViewById<RecyclerView>(R.id.recycler)
                    val jsonValue = GsonUtils.toJson(it.values)
                    val phrases = GsonUtils.fromJson<List<YDPhrasesEntity>>(
                        jsonValue,
                        object : TypeToken<List<YDPhrasesEntity>>() {}.type
                    )
                    recyclerView.layoutManager = LinearLayoutManager(mContext)
                    recyclerView.adapter = PhraseAdapter(mContext, phrases)
                }

                Constants.TYPE_EXPAND_ITEM -> {
                    val recyclerView = holder.itemView.findViewById<RecyclerView>(R.id.recycler)
                    val jsonValue = GsonUtils.toJson(it.values)
                    val derivatives = GsonUtils.fromJson<List<YDDerivatives>>(
                        jsonValue,
                        object : TypeToken<List<YDDerivatives>>() {}.type
                    )
                    recyclerView.layoutManager = LinearLayoutManager(mContext)
                    recyclerView.adapter = ExpandAdapter(mContext, derivatives)
                }

                Constants.TYPE_RELATED_ITEM -> {
                    val recyclerView = holder.itemView.findViewById<RecyclerView>(R.id.recycler)
                    val jsonValue = GsonUtils.toJson(it.values)
                    val relatedWords = GsonUtils.fromJson<List<YDRelatedWords>>(
                        jsonValue,
                        object : TypeToken<List<YDRelatedWords>>() {}.type
                    )
                    recyclerView.layoutManager = LinearLayoutManager(mContext)
                    recyclerView.adapter = RelatedAdapter(mContext, relatedWords)
                }

                else -> {

                }
            }

        }


    }


    fun setNewData(data: List<DictWordEntity>?) {
        mData = data
//        mSelectPosition = -1
        notifyDataSetChanged()
    }

    /**
     * 渲染释义模块
     */
    private fun renderExplain(meanings: ArrayList<*>?): View {
//        if (!detailItem.containsKey("meanings")) {
//            return null
//        }
        val explainView = LinearLayout(mContext).apply { orientation = LinearLayout.VERTICAL }
//        val meanings = detailItem["meanings"] as ArrayList<*>?
        meanings?.let { array ->
            array.forEach { item ->
                // 创建释义item行
                val explainLayout = LinearLayout(mContext)
                explainLayout.orientation = LinearLayout.HORIZONTAL
                explainLayout.gravity = Gravity.CENTER_VERTICAL
                explainLayout.setPadding(0,0,0,SizeUtils.dp2px(10f))
                explainLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT).apply {
                    topMargin = SizeUtils.dp2px(10f)
                }
                item as LinkedTreeMap<*, *>

                val pos = item["pos"] as String?
                val values = item["value"] as ArrayList<*>?
                var txt = pos
                values?.forEach {
                    it as String
                    txt += it
                }

                val explainTxt = BorderedTextView(mContext)
                explainTxt.maxWidth = SizeUtils.dp2px(440f)
                explainTxt.text = txt

                val gptButton = TextView(mContext).apply {
                    val colors = intArrayOf(
                        ContextCompat.getColor(context, R.color.ntt_FFCC00),
                        ContextCompat.getColor(context, R.color.ntt_FFB604)
                    )
                    setDrawableBackground(colors, SizeUtils.dp2px(20f).toFloat())
                    text = context.getString(R.string.gpt_practice)
                    setTextColor(ContextCompat.getColor(context, R.color.ntt_ffffff))
                    textSize = 18f
                    typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    setPadding(
                        SizeUtils.dp2px(18f),
                        SizeUtils.dp2px(8f),
                        SizeUtils.dp2px(18f),
                        SizeUtils.dp2px(8f)
                    )
                    stateListAnimator = AnimatorInflater.loadStateListAnimator(context, R.drawable.btn_press)
                    layoutParams =
                        ConstraintLayout.LayoutParams(
                            ConstraintLayout.LayoutParams.WRAP_CONTENT,
                            ConstraintLayout.LayoutParams.WRAP_CONTENT
                        ).apply {
                            marginStart = SizeUtils.dp2px(20f)
                        }
                    tag = item
                }

                gptButton.setOnClickListener {
                    NLogger.d("DictWordAdapter 点击了 -> $mOnChildClickListener")
                    mOnChildClickListener?.onChildClick(it.tag)
                }

                explainLayout.addView(explainTxt)
                explainLayout.addView(gptButton)
                explainView.addView(explainLayout)

            }
        }
        return explainView
    }

}
